/**
 * @author:albert
 */

package com.bkbw.live.database.net.server;

import java.sql.CallableStatement;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.apache.mina.core.service.IoHandlerAdapter;
import org.apache.mina.core.session.IdleStatus;
import org.apache.mina.core.session.IoSession;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.bkbw.live.battle.database.bean.DBagEquipmentBean;
import com.bkbw.live.battle.database.bean.DBagItemBean;
import com.bkbw.live.battle.database.bean.DBagWeaponBean;
import com.bkbw.live.battle.database.bean.DBodyEquipmentBean;
import com.bkbw.live.battle.database.bean.DCharacterBean;
import com.bkbw.live.common.business.ItemTypeUtil;
import com.bkbw.live.common.dataproto.BattleToDatabasePb.BS2DBBagItemDetailReq;
import com.bkbw.live.common.dataproto.BattleToDatabasePb.BS2DBBagReq;
import com.bkbw.live.common.dataproto.BattleToDatabasePb.BS2DBBuyItemReq;
import com.bkbw.live.common.dataproto.BattleToDatabasePb.BS2DBCharacterReq;
import com.bkbw.live.common.dataproto.BattleToDatabasePb.BS2DBDropBagItemReq;
import com.bkbw.live.common.dataproto.BattleToDatabasePb.BS2DBEquipReq;
import com.bkbw.live.common.dataproto.BattleToDatabasePb.BS2DBSaveCharacterReq;
import com.bkbw.live.common.dataproto.BattleToDatabasePb.BS2DBTableReq;
import com.bkbw.live.common.dataproto.BattleToDatabasePb.BS2DBUseBagItemReq;
import com.bkbw.live.common.dataproto.BattleToDatabasePb.DB2BSBagItemDetailResp;
import com.bkbw.live.common.dataproto.BattleToDatabasePb.DB2BSBagResp;
import com.bkbw.live.common.dataproto.BattleToDatabasePb.DB2BSBuyItemResp;
import com.bkbw.live.common.dataproto.BattleToDatabasePb.DB2BSCharacterResp;
import com.bkbw.live.common.dataproto.BattleToDatabasePb.DB2BSDropBagItemResp;
import com.bkbw.live.common.dataproto.BattleToDatabasePb.DB2BSEquipResp;
import com.bkbw.live.common.dataproto.BattleToDatabasePb.DB2BSSaveCharacterResp;
import com.bkbw.live.common.dataproto.BattleToDatabasePb.DB2BSTableResp;
import com.bkbw.live.common.dataproto.BattleToDatabasePb.DB2BSUseBagItemResp;
import com.bkbw.live.common.dataproto.BattleToDatabasePb.DbBagEquipment;
import com.bkbw.live.common.dataproto.BattleToDatabasePb.DbBagItem;
import com.bkbw.live.common.dataproto.BattleToDatabasePb.DbBagWeapon;
import com.bkbw.live.common.dataproto.BattleToDatabasePb.DbBodyEquipment;
import com.bkbw.live.common.dataproto.BattleToDatabasePb.HeadType;
import com.bkbw.live.common.dataproto.CommonMessagePb.BagItemChangePb;
import com.bkbw.live.common.dataproto.CommonMessagePb.DBagItemPb;
import com.bkbw.live.common.dataproto.CommonMessagePb.DBagItemPbOpTypePb;
import com.bkbw.live.common.dataproto.CommonMessagePb.DCharacterPb;
import com.bkbw.live.common.dataproto.CommonMessagePb.HashLongInt;
import com.bkbw.live.common.dataproto.CommonMessagePb.TripleLongIntIntPb;
import com.bkbw.live.common.dataproto.EnumConfigPb.ResultCode;
import com.bkbw.live.common.net.codec.RawMessageObject;
import com.bkbw.live.common.util.Utils;
import com.bkbw.live.database.net.codec.PackageHead;
import com.bkbw.live.database.util.DatabasePool;
import com.bkbw.live.database.util.DatabaseUtil;
import com.google.protobuf.InvalidProtocolBufferException;

public class DatabaseServerHandler extends IoHandlerAdapter {
	Logger logger = LoggerFactory.getLogger("mylog");
	
	static Map<IoSession,Integer> sessionMap = new HashMap<IoSession,Integer>();
    @Override
	public void sessionCreated(IoSession session) throws Exception {
    	super.sessionCreated(session);
	}
	@Override
	public void sessionClosed(IoSession session) throws Exception {
		// TODO Auto-generated method stub
		super.sessionClosed(session);
		System.out.println("客户端"+sessionMap.get(session)+"正常离开了");
	}
	@Override
    public void exceptionCaught( IoSession session, Throwable cause ) throws Exception
    {
		System.out.println("客户端"+sessionMap.get(session)+"异常离开了");
		cause.printStackTrace();
    }
	
	
	
	
	
	
	public void onMsgTableReq(IoSession session, RawMessageObject rawMessageObject) throws InvalidProtocolBufferException {
		BS2DBTableReq tableReq = BS2DBTableReq.parseFrom(rawMessageObject.getData());
		Connection conn = null;
		try {
			System.out.println("received request for table "+tableReq.getTableName());
			conn = DatabasePool.getConnection();
			int totalNum = DatabaseUtil.getTableRowCount(conn, tableReq.getTableName());
			final int oneTransmit = 50;
			if (totalNum > oneTransmit) {
				JSONArray jsonArray = DatabaseUtil.executeQueryInTrans(conn, "select * from "+tableReq.getTableName());
				//DatabasePool.release(conn);
				int temp = 0;
				while (temp < jsonArray.size()) {
					int remain = jsonArray.size() - temp;
					JSONArray jSubList = new JSONArray();
					int transmit = 0;
					if (remain > oneTransmit) {
						List<JSONObject> subList = jsonArray.subList(temp, temp + oneTransmit);
						jSubList.addAll(subList);
						transmit = oneTransmit;
					}
					else {
						
						List<JSONObject> subList = jsonArray.subList(temp, temp + remain);
						jSubList.addAll(subList);
						transmit = remain;
					}
					DB2BSTableResp.Builder tableRespBuilder = DB2BSTableResp.newBuilder();
					tableRespBuilder.setTableName(tableReq.getTableName());
					tableRespBuilder.setJsonData(jSubList.toString());
					tableRespBuilder.setOffsetRowIndex(temp);
					tableRespBuilder.setRowCount(jSubList.size());
					tableRespBuilder.setTotalRowCount(totalNum);
					temp += transmit;
					DB2BSTableResp tableResp = tableRespBuilder.build();
					System.out.println("send data len " + tableResp.getSerializedSize());
					//tableResp.toByteArray()
					RawMessageObject respMessage = new RawMessageObject((short)HeadType.DB2BS_TABLE_RESP_VALUE, tableResp.toByteArray(), session);
					session.write(respMessage);
				}
			}
			else {
				JSONArray jsonArray = DatabaseUtil.executeQueryInTrans(conn, "select * from "+tableReq.getTableName());
				//DatabasePool.release(conn);
				System.out.println("db request for table "+tableReq.getTableName() + "ok");
				DB2BSTableResp.Builder tableRespBuilder = DB2BSTableResp.newBuilder();
				tableRespBuilder.setTableName(tableReq.getTableName());
				tableRespBuilder.setJsonData(jsonArray.toString());
				tableRespBuilder.setRowCount(jsonArray.size());
				tableRespBuilder.setTotalRowCount(totalNum);
				tableRespBuilder.setOffsetRowIndex(0);
				DB2BSTableResp tableResp = tableRespBuilder.build();
				System.out.println("send data len " + tableResp.getSerializedSize());
				//tableResp.toByteArray()
				RawMessageObject respMessage = new RawMessageObject((short)HeadType.DB2BS_TABLE_RESP_VALUE, tableResp.toByteArray(), session);
				session.write(respMessage);
			}
			
			
		}
		catch (Exception e){
			e.printStackTrace();
		}
		finally {
			try {
				if (conn != null) 
					DatabasePool.release(conn);
			}
			catch (Exception e){
				e.printStackTrace();
			}
		}
		
	}
	
	public void onMsgCharacterReq(IoSession session, RawMessageObject rawMessageObject) throws InvalidProtocolBufferException{
		Connection conn = null;
		BS2DBCharacterReq characterReq = BS2DBCharacterReq.parseFrom(rawMessageObject.getData());
		DB2BSCharacterResp.Builder respBuilder = DB2BSCharacterResp.newBuilder();
		try {
			conn = DatabasePool.getConnection();
    		
    		CallableStatement callableStatement = conn.prepareCall("{call proc_read_character(?,?)}");
    		callableStatement.setInt(1, characterReq.getCharId());
    		callableStatement.registerOutParameter(2, java.sql.Types.INTEGER); 
    		ResultSet rs=null;
    		boolean hasResultSet = callableStatement.execute(); 
    		int userId = callableStatement.getInt(2);
    		//System.out.println("userid " + userId);
    		// process characterinfo
    		
    		if (hasResultSet) {
    			
    			rs = callableStatement.getResultSet();
    			// process characterinfo
    			List<DCharacterPb> list1 = DatabaseUtil.resultSetToProtoBean(rs, DCharacterPb.class, DCharacterPb.Builder.class);
    			Utils.dumpList(list1);
    			if (list1.size() == 0) {
    				logger.debug("handleCharacterReq db no data");
        			respBuilder.setResult(ResultCode.Failed);
        			respBuilder.setDescription("no data");
        			return;
    			}
    			respBuilder.setDbCharacterInfo(list1.get(0));
    			
    			callableStatement.getMoreResults();
    			rs = callableStatement.getResultSet();
    			List<DbBodyEquipment> list2 = DatabaseUtil.resultSetToProtoBean(rs, DbBodyEquipment.class, DbBodyEquipment.Builder.class);
    			Utils.dumpList(list2);
    			respBuilder.setDbBodyEquipment(list2.get(0));
    			
    			callableStatement.getMoreResults();
    			rs = callableStatement.getResultSet();
    			List<DbBagItem> list3 = DatabaseUtil.resultSetToProtoBean(rs, DbBagItem.class, DbBagItem.Builder.class);
    			Utils.dumpList(list3);
    			for (DbBagItem dbBagItem : list3) {
					respBuilder.addBagItem(dbBagItem);
				}
    			
    			callableStatement.getMoreResults();
    			rs = callableStatement.getResultSet();
    			List<DbBagEquipment> list4 = DatabaseUtil.resultSetToProtoBean(rs, DbBagEquipment.class, DbBagEquipment.Builder.class);
    			Utils.dumpList(list4);
    			for (DbBagEquipment dbBagEquipment : list4) {
					respBuilder.addBagEquipment(dbBagEquipment);
				}
    			
    			callableStatement.getMoreResults();
    			rs = callableStatement.getResultSet();
    			List<DbBagWeapon> list5 = DatabaseUtil.resultSetToProtoBean(rs, DbBagWeapon.class, DbBagWeapon.Builder.class);
    			Utils.dumpList(list5);
    			for (DbBagWeapon dbBagWeapon : list5) {
					respBuilder.addBagWeapon(dbBagWeapon);
				}
    			
    			respBuilder.setResult(ResultCode.Succeed);
    		}
    		// no resultset readed
    		else {
    			respBuilder.setResult(ResultCode.Failed);
    			respBuilder.setDescription("db read fail");
    		}
    		
		}
		catch (Exception e){
			
			respBuilder.setResult(ResultCode.Failed);
			respBuilder.setDescription(Utils.exceptionStack(e));
		}
		finally {
			if (conn != null) {
				try {
					DatabasePool.release(conn);
				}
				catch (SQLException e){
					
				}
			}
			respBuilder.setCharId(characterReq.getCharId());
			respBuilder.setTableId(characterReq.getTableId());
			respBuilder.setSessionId(characterReq.getSessionId());
			respBuilder.setHeadType(HeadType.DB2BS_CHARACTER_RESP);
			DB2BSCharacterResp resp = respBuilder.build();
			RawMessageObject respMessage = new RawMessageObject((short)HeadType.DB2BS_CHARACTER_RESP_VALUE, resp.toByteArray(), session);
			session.write(respMessage);
			logger.debug("write DB2BS_CHARACTER_RESP");
		}
	}
	
	public void onMsgBagReq(IoSession session, RawMessageObject rawMessageObject) throws InvalidProtocolBufferException{
		Connection conn = null;
		BS2DBBagReq bagReq = BS2DBBagReq.parseFrom(rawMessageObject.getData());
		DB2BSBagResp.Builder bagRespBuilder = DB2BSBagResp.newBuilder();
		try {
			conn = DatabasePool.getConnection();
    		
    		CallableStatement callableStatement = conn.prepareCall("{call proc_read_bag(?)}");
    		callableStatement.setInt(1, bagReq.getCharId());
    		ResultSet rs=null;
    		boolean hasResultSet = callableStatement.execute(); 
    		int userId = callableStatement.getInt(2);
    		//System.out.println("userid " + userId);
    		// process characterinfo
    		
    		if (hasResultSet) {
    			
    			rs = callableStatement.getResultSet();
    			
    			List<DbBagItem> list1 = DatabaseUtil.resultSetToProtoBean(rs, DbBagItem.class, DbBagItem.Builder.class);
    			Utils.dumpList(list1);
    			for (DbBagItem dbBagItem : list1) {
    				bagRespBuilder.addBagItem(dbBagItem);
				}
    			
    			callableStatement.getMoreResults();
    			rs = callableStatement.getResultSet();
    			List<DbBagEquipment> list2 = DatabaseUtil.resultSetToProtoBean(rs, DbBagEquipment.class, DbBagEquipment.Builder.class);
    			Utils.dumpList(list2);
    			for (DbBagEquipment dbBagEquipment : list2) {
    				bagRespBuilder.addBagEquipment(dbBagEquipment);
				}
    			
    			callableStatement.getMoreResults();
    			rs = callableStatement.getResultSet();
    			List<DbBagWeapon> list3 = DatabaseUtil.resultSetToProtoBean(rs, DbBagWeapon.class, DbBagWeapon.Builder.class);
    			Utils.dumpList(list3);
    			for (DbBagWeapon dbBagWeapon : list3) {
    				bagRespBuilder.addBagWeapon(dbBagWeapon);
				}
    			
    			bagRespBuilder.setResult(ResultCode.Succeed);
    		}
    		// no resultset readed
    		else {
    			bagRespBuilder.setResult(ResultCode.Failed);
    			bagRespBuilder.setDescription("db read fail");
    		}
    		
		}
		catch (Exception e){
			
			bagRespBuilder.setResult(ResultCode.Failed);
			bagRespBuilder.setDescription(Utils.exceptionStack(e));
		}
		finally {
			if (conn != null) {
				try {
					DatabasePool.release(conn);
				}
				catch (SQLException e){
					
				}
			}
			bagRespBuilder.setCharId(bagReq.getCharId());
			bagRespBuilder.setTableId(bagReq.getTableId());
			bagRespBuilder.setSessionId(bagReq.getSessionId());
			bagRespBuilder.setHeadType(HeadType.DB2BS_BAG_RESP);
			DB2BSBagResp resp = bagRespBuilder.build();
			RawMessageObject respMessage = new RawMessageObject((short)HeadType.DB2BS_BAG_RESP_VALUE, resp.toByteArray(), session);
			session.write(respMessage);
			logger.debug("write DB2BS_BAG_RESP_VALUE");
		}
	}
	
	public void onMsgBagItemDetailReq(IoSession session, RawMessageObject rawMessageObject) throws InvalidProtocolBufferException{
		Connection conn = null;
		BS2DBBagItemDetailReq detailReq = BS2DBBagItemDetailReq.parseFrom(rawMessageObject.getData());
		DB2BSBagItemDetailResp.Builder respBuilder = DB2BSBagItemDetailResp.newBuilder();
		try {
			
			DatabaseUtil.executeQueryReturnBean(DatabasePool.getDataSource(), "select * from d_bagitems where uid="+detailReq.getUid(), DBagItemBean.class);
		}
		catch (Exception e) {
			
		}
		finally {
			
		}
		
	}
	
	
	private<T> int beanToUpdate(T bean) throws Exception {
		String sql = DatabaseUtil.beanToUpdate(bean);
		logger.debug(sql);
		return DatabaseUtil.executeUpdate(DatabasePool.getDataSource(), sql);
	}
	
	private<T> int beanToUpdateInTrans(T bean, Connection conn) throws Exception {
		String sql = DatabaseUtil.beanToUpdate(bean);
		logger.debug(sql);
		return DatabaseUtil.executeUpdateInTrans(conn, sql);
	}
	
	private<T> int beanToInsert(T bean) throws Exception {
		String sql = DatabaseUtil.beanToInsert(bean);
		logger.debug(sql);
		return DatabaseUtil.executeUpdate(DatabasePool.getDataSource(), sql);
	}
	
	private<T> int beanToInsertInTrans(T bean, Connection conn) throws Exception {
		String sql = DatabaseUtil.beanToInsert(bean);
		logger.debug(sql);
		return DatabaseUtil.executeUpdateInTrans(conn, sql);
	}
	
	private<T> int beanToDelete(T bean) throws Exception {
		String sql = DatabaseUtil.beanToDelete(bean);
		logger.debug(sql);
		return DatabaseUtil.executeUpdate(DatabasePool.getDataSource(), sql);
	}
	
	private<T> int beanToDeleteInTrans(T bean, Connection conn) throws Exception {
		String sql = DatabaseUtil.beanToDelete(bean);
		logger.debug(sql);
		return DatabaseUtil.executeUpdateInTrans(conn, sql);
	}
	
	private<T> int processSql(BagItemChangePb changeInfo, T bean) throws Exception{
		int ret = 0;
		DBagItemPb bagItemPb = changeInfo.getBagItem();
		switch (changeInfo.getDbType().getNumber()) {
		case DBagItemPbOpTypePb.DBagItemPbDbTypePb_Insert_VALUE:
		{
			ret = beanToInsert(bean);
			break;
		}
		case DBagItemPbOpTypePb.DBagItemPbDbTypePb_Delete_VALUE:
		{
			ret = beanToDelete(bean);
			break;
		}
		case DBagItemPbOpTypePb.DBagItemPbDbTypePb_UpdateNumber_VALUE:
		{
			if (bagItemPb.getNumber() == 0) {
				ret = beanToDelete(bean);
			}
			else {
				ret = beanToUpdate(bean);
			}
			break;
		}
		case DBagItemPbOpTypePb.DBagItemPbDbTypePb_UpdateContent_VALUE:
		{
			if (bagItemPb.getNumber() == 0) {
				ret = beanToDelete(bean);
			}
			else {
				ret = beanToUpdate(bean);
			}
			break;
		}
		case DBagItemPbOpTypePb.DBagItemPbDbTypePb_UpdateEquip_VALUE:
		{
			ret = beanToUpdate(bean);
			break;
		}
		}
		return ret;
	}
	
	private<T> int processSqlInTrans(BagItemChangePb changeInfo, T bean, Connection conn) throws Exception{
		int ret = 0;
		DBagItemPb bagItemPb = changeInfo.getBagItem();
		switch (changeInfo.getDbType().getNumber()) {
		case DBagItemPbOpTypePb.DBagItemPbDbTypePb_Insert_VALUE:
		{
			ret = beanToInsertInTrans(bean, conn);
			break;
		}
		case DBagItemPbOpTypePb.DBagItemPbDbTypePb_Delete_VALUE:
		{
			ret = beanToDeleteInTrans(bean, conn);
			break;
		}
		case DBagItemPbOpTypePb.DBagItemPbDbTypePb_UpdateNumber_VALUE:
		{
			if (bagItemPb.getNumber() == 0) {
				ret = beanToDeleteInTrans(bean, conn);
			}
			else {
				ret = beanToDeleteInTrans(bean, conn);
			}
			break;
		}
		case DBagItemPbOpTypePb.DBagItemPbDbTypePb_UpdateContent_VALUE:
		{
			if (bagItemPb.getNumber() == 0) {
				ret = beanToDeleteInTrans(bean, conn);
			}
			else {
				ret = beanToUpdateInTrans(bean, conn);
			}
			break;
		}
		case DBagItemPbOpTypePb.DBagItemPbDbTypePb_UpdateEquip_VALUE:
		{
			ret = beanToUpdateInTrans(bean, conn);
			break;
		}
		}
		return ret;
	}
	
	private boolean bagItemChange(List<BagItemChangePb> changeList){
		try {
			for (BagItemChangePb changeInfo : changeList) {
				if (ItemTypeUtil.isItem(changeInfo.getItemType())) {
					DBagItemBean bagItemBean = new DBagItemBean();
					Utils.copyFieldsToBean(changeInfo.getBagItem(), bagItemBean);
					processSql(changeInfo, bagItemBean);
				}
				else if (ItemTypeUtil.isEquipment(changeInfo.getItemType())) {
					DBagEquipmentBean bagEquipmentBean = new DBagEquipmentBean();
					Utils.copyFieldsToBean(changeInfo.getBagItem(), bagEquipmentBean);
					processSql(changeInfo, bagEquipmentBean);
				}
				else if (ItemTypeUtil.isWeapon(changeInfo.getItemType())) {
					DBagWeaponBean bagWeaponBean = new DBagWeaponBean();
					Utils.copyFieldsToBean(changeInfo.getBagItem(), bagWeaponBean);
					processSql(changeInfo, bagWeaponBean);
				}
				else if (ItemTypeUtil.isCollection(changeInfo.getItemType())) {
					DBagItemBean bagItemBean = new DBagItemBean();
					Utils.copyFieldsToBean(changeInfo.getBagItem(), bagItemBean);
					processSql(changeInfo, bagItemBean);
				}
				else {
					continue;
				}
				
			}
			return true;
		}
		catch (Exception e){
			return false;
		}
		
		
	}
	
	private boolean bagItemChangeInTrans(List<BagItemChangePb> changeList, Connection conn){
		try {
			for (BagItemChangePb changeInfo : changeList) {
				if (ItemTypeUtil.isItem(changeInfo.getItemType())) {
					DBagItemBean bagItemBean = new DBagItemBean();
					Utils.copyFieldsToBean(changeInfo.getBagItem(), bagItemBean);
					if (processSqlInTrans(changeInfo, bagItemBean, conn) <= 0) {
						return false;
					}
				}
				else if (ItemTypeUtil.isEquipment(changeInfo.getItemType())) {
					DBagEquipmentBean bagEquipmentBean = new DBagEquipmentBean();
					Utils.copyFieldsToBean(changeInfo.getBagItem(), bagEquipmentBean);
					if (processSqlInTrans(changeInfo, bagEquipmentBean, conn) <= 0) {
						return false;
					}
				}
				else if (ItemTypeUtil.isWeapon(changeInfo.getItemType())) {
					DBagWeaponBean bagWeaponBean = new DBagWeaponBean();
					Utils.copyFieldsToBean(changeInfo.getBagItem(), bagWeaponBean);
					if (processSqlInTrans(changeInfo, bagWeaponBean, conn) <= 0) {
						return false;
					}
				}
				else if (ItemTypeUtil.isCollection(changeInfo.getItemType())) {
					DBagItemBean bagItemBean = new DBagItemBean();
					Utils.copyFieldsToBean(changeInfo.getBagItem(), bagItemBean);
					if (processSqlInTrans(changeInfo, bagItemBean, conn) <= 0) {
						return false;
					}
				}
				else {
					return false;
				}
				
			}
			return true;
		}
		catch (Exception e){
			return false;
		}
		
		
	}
	
	public void onMsgDropBagItemReq(IoSession session, RawMessageObject rawMessageObject) throws InvalidProtocolBufferException{
		Connection conn = null;
		BS2DBDropBagItemReq dropReq = BS2DBDropBagItemReq.parseFrom(rawMessageObject.getData());
		DB2BSDropBagItemResp.Builder respBuilder = DB2BSDropBagItemResp.newBuilder();
		try {
			
			if (bagItemChange(dropReq.getDropItemsList())) {
				respBuilder.setResult(ResultCode.Succeed);
			}
			else {
				respBuilder.setResult(ResultCode.Failed);
			}
			//DatabaseUtil.executeQueryReturnBean(DatabasePool.getDataSource(), "select * from d_bagitems where uid="+detailReq.getUid(), DBagItemBean.class);
			//respBuilder.setResult(ResultCode.Succeed);
		}
		catch (Exception e) {
			e.printStackTrace();
			respBuilder.setResult(ResultCode.Failed);
			respBuilder.setDescription(Utils.exceptionStack(e));
		}
		finally {
			respBuilder.setCharId(dropReq.getCharId());
			respBuilder.setTableId(dropReq.getTableId());
			respBuilder.setSessionId(dropReq.getSessionId());
			respBuilder.setHeadType(HeadType.DB2BS_DROP_BAG_ITEM_RESP);
			DB2BSDropBagItemResp resp = respBuilder.build();
			RawMessageObject respMessage = new RawMessageObject((short)HeadType.DB2BS_DROP_BAG_ITEM_RESP_VALUE, resp.toByteArray(), session);
			session.write(respMessage);
		}
	}
	
	public void onMsgUseBagItemReq(IoSession session, RawMessageObject rawMessageObject) throws InvalidProtocolBufferException{
		Connection conn = null;
		BS2DBUseBagItemReq req = BS2DBUseBagItemReq.parseFrom(rawMessageObject.getData());
		DB2BSUseBagItemResp.Builder respBuilder = DB2BSUseBagItemResp.newBuilder();
		try {
			if (bagItemChange(req.getUseItemsList())) {
				respBuilder.setResult(ResultCode.Succeed);
			}
			else {
				respBuilder.setResult(ResultCode.Failed);
			}
			//DatabaseUtil.executeQueryReturnBean(DatabasePool.getDataSource(), "select * from d_bagitems where uid="+detailReq.getUid(), DBagItemBean.class);
			
		}
		catch (Exception e) {
			e.printStackTrace();
			respBuilder.setResult(ResultCode.Failed);
			respBuilder.setDescription(Utils.exceptionStack(e));
		}
		finally {
			respBuilder.setCharId(req.getCharId());
			respBuilder.setTableId(req.getTableId());
			respBuilder.setSessionId(req.getSessionId());
			respBuilder.setHeadType(HeadType.DB2BS_USE_BAG_ITEM_RESP);
			DB2BSUseBagItemResp resp = respBuilder.build();
			RawMessageObject respMessage = new RawMessageObject((short)HeadType.DB2BS_USE_BAG_ITEM_RESP_VALUE, resp.toByteArray(), session);
			session.write(respMessage);
		}
	}
	
	
	public void onMsgSaveCharacterReq(IoSession session, RawMessageObject rawMessageObject) throws InvalidProtocolBufferException{
		Connection conn = null;
		BS2DBSaveCharacterReq req = BS2DBSaveCharacterReq.parseFrom(rawMessageObject.getData());
		DB2BSSaveCharacterResp.Builder respBuilder = DB2BSSaveCharacterResp.newBuilder();
		try {
			DCharacterBean characterBean = new DCharacterBean();
			Utils.copyFieldsToBean(req.getCharacter(), characterBean);
			beanToUpdate(characterBean);
			respBuilder.setResult(ResultCode.Succeed);
			//DatabaseUtil.executeQueryReturnBean(DatabasePool.getDataSource(), "select * from d_bagitems where uid="+detailReq.getUid(), DBagItemBean.class);
			
		}
		catch (Exception e) {
			e.printStackTrace();
			respBuilder.setResult(ResultCode.Failed);
			respBuilder.setDescription(Utils.exceptionStack(e));
		}
		finally {
			
			respBuilder.setHeadType(HeadType.DB2BS_SAVE_CHARACTER_RESP);
			DB2BSSaveCharacterResp resp = respBuilder.build();
			RawMessageObject respMessage = new RawMessageObject((short)HeadType.DB2BS_SAVE_CHARACTER_RESP_VALUE, resp.toByteArray(), session);
			session.write(respMessage);
		}
	}
	
	public void onMsgBuyItemReq(IoSession session, RawMessageObject rawMessageObject) throws InvalidProtocolBufferException{
		Connection conn = null;
		BS2DBBuyItemReq req = BS2DBBuyItemReq.parseFrom(rawMessageObject.getData());
		DB2BSBuyItemResp.Builder respBuilder = DB2BSBuyItemResp.newBuilder();
		try {
			if (bagItemChange(req.getBuyItemsList())) {
				respBuilder.setResult(ResultCode.Succeed);
			}
			else {
				respBuilder.setResult(ResultCode.Failed);
			}
			
			respBuilder.setResult(ResultCode.Succeed);
			//DatabaseUtil.executeQueryReturnBean(DatabasePool.getDataSource(), "select * from d_bagitems where uid="+detailReq.getUid(), DBagItemBean.class);
			
		}
		catch (Exception e) {
			e.printStackTrace();
			respBuilder.setResult(ResultCode.Failed);
			respBuilder.setDescription(Utils.exceptionStack(e));
		}
		finally {
			respBuilder.setCharId(req.getCharId());
			respBuilder.setTableId(req.getTableId());
			respBuilder.setSessionId(req.getSessionId());
			respBuilder.setHeadType(HeadType.DB2BS_BUY_ITEM_RESP);
			DB2BSBuyItemResp resp = respBuilder.build();
			RawMessageObject respMessage = new RawMessageObject((short)HeadType.DB2BS_BUY_ITEM_RESP_VALUE, resp.toByteArray(), session);
			session.write(respMessage);
		}
	}
	
	
	public void onMsgEquipReq(IoSession session, RawMessageObject rawMessageObject) throws InvalidProtocolBufferException{
		Connection conn = null;
		BS2DBEquipReq req = BS2DBEquipReq.parseFrom(rawMessageObject.getData());
		DB2BSEquipResp.Builder respBuilder = DB2BSEquipResp.newBuilder();
		try {
			conn = DatabasePool.beginTransaction();
			if (bagItemChange(req.getEquipItemsList())) {
				respBuilder.setResult(ResultCode.Succeed);
			}
			else {
				respBuilder.setResult(ResultCode.Failed);
			}
			DbBodyEquipment dbBodyEquipment = req.getOnBodyEquipment();
			DBodyEquipmentBean bean = new DBodyEquipmentBean();
			Utils.copyFieldsToBean(dbBodyEquipment, bean);
			bean.setCharId(req.getCharId());
			beanToUpdateInTrans(bean, conn);
			
			respBuilder.setResult(ResultCode.Succeed);
			//DatabaseUtil.executeQueryReturnBean(DatabasePool.getDataSource(), "select * from d_bagitems where uid="+detailReq.getUid(), DBagItemBean.class);
			DatabasePool.commitTransaction(conn);
		}
		catch (Exception e) {
			e.printStackTrace();
			try {
				DatabasePool.rollbackTransaction(conn);
			}
			catch (Exception ee) {
				
			}
			respBuilder.setResult(ResultCode.Failed);
			respBuilder.setDescription(Utils.exceptionStack(e));
		}
		finally {
			respBuilder.setCharId(req.getCharId());
			respBuilder.setTableId(req.getTableId());
			respBuilder.setSessionId(req.getSessionId());
			respBuilder.setHeadType(HeadType.DB2BS_BUY_ITEM_RESP);
			DB2BSEquipResp resp = respBuilder.build();
			RawMessageObject respMessage = new RawMessageObject((short)HeadType.DB2BS_EQUIP_RESP_VALUE, resp.toByteArray(), session);
			session.write(respMessage);
		}
	}
	
    @Override
    public void messageReceived( IoSession session, Object message ) throws Exception
    {
    	RawMessageObject rawMessageObject = (RawMessageObject)message;
    	if (rawMessageObject.getHead() == HeadType.BS2DB_TABLE_REQ_VALUE) {
    		onMsgTableReq(session, rawMessageObject);
    		
    	}
    	else if (rawMessageObject.getHead() == HeadType.BS2DB_CHARACTER_REQ_VALUE) {
    		onMsgCharacterReq(session, rawMessageObject);
    		
    	}
    	else if (rawMessageObject.getHead() == HeadType.BS2DB_BAG_REQ_VALUE) {
    		
    	}
    	else if (rawMessageObject.getHead() == HeadType.BS2DB_BAG_ITEM_DETAIL_REQ_VALUE) {
    		
    	}
    	else if (rawMessageObject.getHead() == HeadType.BS2DB_DROP_BAG_ITEM_REQ_VALUE) {
    		onMsgDropBagItemReq(session, rawMessageObject);
    	}
    	else if (rawMessageObject.getHead() == HeadType.BS2DB_USE_BAG_ITEM_REQ_VALUE) {
    		onMsgUseBagItemReq(session, rawMessageObject);
    	}
    	else if (rawMessageObject.getHead() == HeadType.BS2DB_SAVE_CHARACTER_REQ_VALUE) {
    		onMsgSaveCharacterReq(session, rawMessageObject);
    	}
    	else if (rawMessageObject.getHead() == HeadType.BS2DB_BUY_ITEM_REQ_VALUE) {
    		onMsgBuyItemReq(session, rawMessageObject);
    	}
    	else if (rawMessageObject.getHead() == HeadType.BS2DB_EQUIP_REQ_VALUE) {
    		onMsgEquipReq(session, rawMessageObject);
    	}
    	
    }
    
    @Override
    public void sessionIdle( IoSession session, IdleStatus status ) throws Exception
    {
        //System.out.println( "IDLE " + session.getIdleCount( status ));
    }
    
}
